// pages/scan/scan.js
var netWork = require('../../utils/netWork.js');
var api = require('../../utils/api.js');
var apiCode = require('../../utils/openApiCode.js');
var branch = require('../../utils/branchMiniapp.js');
const util = require('../../utils/util');
const log = require('../../utils/logs.js');
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        imagesUrl: getApp().globalData.imagesUrl,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        api.showLoading('正在加载中...');
        api.judgeNetworkStatus(function (res) {
            if ("none" == res) return;
        })
        try {
            const {
                SDKVersion = ''
            } = wx.getSystemInfoSync();
            log.info(SDKVersion)
            const compatibility = util.compareVersion(SDKVersion, '2.2.2');
            log.info(compatibility)
            if (compatibility == -1) {
                wx.showModal({
                    content: '您的微信版本过低，请升级后再来吧~',
                    confirmText: '我知道了',
                    showCancel: false
                });
                return;
            }
        } catch (e) {}
        try {
            // 检测是否可以调用getUpdateManager检查更新
            if (!wx.canIUse("getUpdateManager")) return;
            let updateManager = wx.getUpdateManager();
            // 获取全局唯一的版本更新管理器，用于管理小程序更新
            updateManager.onCheckForUpdate(function (res) {
                log.info(res)
                // 监听向微信后台请求检查更新结果事件
                log.info("是否有新版本：" + res.hasUpdate);
                if (res.hasUpdate) {
                    //如果有新版本
                    // 小程序有新版本，会主动触发下载操作
                    updateManager.onUpdateReady(function () {
                        //当新版本下载完成，会进行回调
                        wx.showModal({
                            title: '更新提示',
                            content: '新版本已经准备好，单击确定重启小程序',
                            showCancel: false,
                            success: function (res) {
                                if (res.confirm) {
                                    // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启小程序
                                    updateManager.applyUpdate();
                                }
                            }
                        })
                    })
                    // 小程序有新版本，会主动触发下载操作（无需开发者触发）
                    updateManager.onUpdateFailed(function () {
                        //当新版本下载失败，会进行回调
                        wx.showModal({
                            title: '提示',
                            content: '检查到有新版本，但下载失败，请稍后尝试',
                            showCancel: false,
                        })
                    })
                }
            });
        } catch (e) {
            e
        }
        var that = this;
        // 链接带过来的二维码
        log.info("[链接中的参数]" + JSON.stringify(options));
        console.log("[链接中的参数]" + JSON.stringify(options));


        if (options.q) {
            var str = decodeURIComponent(options.q);
            var index = str.lastIndexOf("\/");
            str = str.substring(index + 1, str.length);
            if (options.q.indexOf('code') != -1) { //宴席
                wx.setStorageSync('qrCodeFeast', str);
                wx.removeStorageSync('qrCode');
                console.info("[存入session中的宴席二维码]" + wx.getStorageSync('qrCodeFeast'));
            } else {
                wx.setStorageSync('qrCode', str);
                wx.removeStorageSync('qrCodeFeast');
                console.log("[存入session中的二维码]" + wx.getStorageSync('qrCode'));

            }

        }
        wx.removeStorageSync('prizeList');
        wx.removeStorageSync('isShowPrizes');
        /**
         * 判断链接带过来的二维码和session中二维码是否有值
         */
        //userid
        if (options.userId) {
            wx.setStorageSync('userId', options.userId);
        }

        log.info("[存入session中的userId]" + wx.getStorageSync('userId'));
        // 判断是否有userId，跳转h5进行授权
        if (wx.getStorageSync('userId') == null || wx.getStorageSync('userId') == '' || wx.getStorageSync('h5Auth') == null || wx.getStorageSync('h5Auth') == '') {
            log.info("[跳转webview/webview?intoType=scan]")
            wx.setStorageSync('h5Auth', 1);
            console.info("[存入session中的h5Auth]" + wx.getStorageSync('h5Auth'))
            //没有userId，调用获取userId接口
            wx.redirectTo({
                url: '../webview/webview?intoType=scan',
            })
        } else {

            if (wx.getStorageSync('qrCode') == '' && wx.getStorageSync('qrCodeFeast') == '') { //无码
                netWork.POST('/getLastScanProductType', {
                    data: {
                        userId: wx.getStorageSync('userId')
                    },
                    success: function (res) {
                        if (res.data.retCode == "0000") {
                            if (res.data.data) {
                                if (res.data.data.productType && res.data.data.productType == 4) {
                                    console.log('上一次分支：' + res.data.data.productType);
                                    //保存当前分支
                                    wx.setStorageSync('productType', res.data.data.productType);
                                    wx.redirectTo({
                                        url: '../xinyouranPage/index/index',
                                    })
                                    return;

                                }
                                if (res.data.data.productType && res.data.data.productType == 1) {
                                    console.log('上一次分支：' + res.data.data.productType);
                                    //保存当前分支
                                    wx.setStorageSync('productType', res.data.data.productType);
                                    wx.redirectTo({
                                        url: '../jingdianPage/index/index',
                                    })
                                    return;
                                }
                                if (res.data.data.productType && res.data.data.productType == 2) {
                                    console.log('上一次分支：' + res.data.data.productType);
                                    //保存当前分支
                                    wx.setStorageSync('productType', res.data.data.productType);
                                    wx.redirectTo({
                                        url: '../index/index',
                                    })
                                    return;
                                }

                                wx.redirectTo({
                                    url: '../commonPage/index/index',
                                })

                            } else {
                                wx.redirectTo({
                                    url: '../commonPage/index/index',
                                })
                                return;
                            }

                        } else {
                            wx.redirectTo({
                                url: '../commonPage/index/index',
                            })
                            return;
                        }

                    },
                    fail: function () {
                        wx.redirectTo({
                            url: '../commonPage/index/index',
                        })
                    }
                })


                return;
            }
            let code = ''; //本次扫码
            let barcodeType = ''; //码类型
            if (wx.getStorageSync('qrCode') != undefined && wx.getStorageSync('qrCode') != '') {
                code = wx.getStorageSync('qrCode');
            }
            if (wx.getStorageSync('qrCodeFeast') != undefined && wx.getStorageSync('qrCodeFeast') != '') {
                code = wx.getStorageSync('qrCodeFeast');
                barcodeType = 1;
            }
            netWork.POST('/check', {
                data: {
                    qrcodeAPublish: code,
                    userId: wx.getStorageSync('userId'),
                    barcodeType: barcodeType
                },
                success: function (res) {
                    api.cancelLoading();
                    if (res.data.retCode == undefined) {
                        //跳转温馨提示页面
                        wx.redirectTo({
                            url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                        })
                        return;
                    }

                    //分支跳转路径
                    let miniAppUrl = res.data.data.miniAppUrl;
                    //产品分支类型
                    let productType = res.data.data.productType;
                    let userType = res.data.data.userType;
                    let retCode = res.data.retCode;
                    let isNewTypeUser = res.data.data.isNewTypeUser;
                    let phone = res.data.data.phone;
                    if (phone) {
                        wx.setStorageSync('userPhone', phone);
                    }
                    //保存当前分支
                    wx.setStorageSync('productType', productType);
                    //客服电话
                    if (res.data.data.servicePhone != "" && res.data.data.servicePhone != null) {
                        wx.setStorageSync('servicePhone', res.data.data.servicePhone);
                    }
                    //根据用户类型来判断跳转页面
                    if (userType != "" && userType != null && userType == 3) {
                        //TODO 黑名单跳转 温馨提示页面
                        wx.redirectTo({
                            url: '../prompt/prompt',
                        })
                        return;
                    }

                    //先判断是否为宴席分支
                    if (barcodeType == 1) {
                        if (retCode != '0000' && productType == undefined) {
                            wx.redirectTo({
                                url: branch.xhtx_jiang.error_url + '?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
                            })
                            return;
                        }
                        if (phone && phone != null && phone != '') {
                            if (res.data.data.isBanquetMaster) { //是历史席主身份， 
                                if (res.data.data.isThisBanquetMaster) { // 手机号匹配
                                    if (res.data.data.isBindMaster) { //已绑定
                                        that.queryInfo(res.data.data.isNewBanquetMaster);
                                        return;
                                    } else { //去绑定
                                        that.bindFeast(res.data.data.isNewBanquetMaster);
                                        return;
                                    }
                                } else { // 手机号不匹配，去不是席主页面
                                    that.bindFeast(res.data.data.isNewBanquetMaster);
                                    
                                    return;
                                }
                            } else { //不是历史的席主身份， 
                                if (res.data.data.isThisBanquetMaster) { //手机号匹配,去绑定
                                    that.bindFeast(res.data.data.isNewBanquetMaster);
                                    return;
                                } else { //不匹配，去活动介绍页
                                    wx.redirectTo({
                                        url: '/pages/feastPage/notOwner/notOwner',
                                    })
                                    return;
                                }
                                
                            }

                        } else {
                            wx.redirectTo({
                                url: '../feastPage/authorization/authorization?isBanquetMaster=' + res.data.data.isNewBanquetMaster,
                            })
                        }

                        return;
                    }

                    //先判断睿
                    if (productType == 3) {
                        wx.redirectTo({
                            url: branch.xhtx_rui.notAct_url,
                        })
                        return;
                    }
                    if (retCode != '0000' && productType == undefined) {
                        wx.redirectTo({
                            url: branch.xhtx_jiang.error_url + '?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
                        })
                        return;
                    }
                    //判断心悠然
                    if (productType == 4) {
                        if (retCode != '0000') {
                            wx.redirectTo({
                                url: branch.xyr.error_url + '?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
                            })
                            return;
                        }
                        wx.redirectTo({
                            url: isNewTypeUser ? branch.xyr.newUser_url : branch.xyr.index_url,
                        })
                        return;

                    }
                    //经典-浓、酱
                    if (productType == 2) {
                        if (retCode != '0000') {
                            wx.redirectTo({
                                url: branch.xhtx_jiang.error_url + '?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
                            })
                            return;
                        }
                        wx.redirectTo({
                            url: isNewTypeUser ? branch.xhtx_jiang.newUser_url : branch.xhtx_jiang.index_url,
                        })
                        return;

                    }
                    if (productType == 1) {
                        if (retCode != '0000') {
                            wx.redirectTo({
                                url: branch.xhtx_nong.error_url + '?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
                            })
                            return;
                        }
                        wx.redirectTo({
                            url: isNewTypeUser ? branch.xhtx_nong.newUser_url : branch.xhtx_nong.index_url,
                        })
                        return;

                    }
                },
                fail: function () {
                    //跳转温馨提示页面
                    wx.redirectTo({
                        url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                    })
                    return;
                }
            });



        }
    },
    queryInfo(isNewBanquetMaster) {
        console.log('bindFeast==>'+isNewBanquetMaster)
        const that = this;
        netWork.POST_Json('banquet/info', {
            data: {
                qrcodeAPublish: wx.getStorageSync('qrCodeFeast'),
            },
            success: function (res) {
                if (res.data.retCode == undefined) {
                    wx.showToast({
                        title: '操作失败，稍后重试',
                        icon: 'none'
                    })
                }
                if (res.data.retCode == '0000') {
                    let status = res.data.data.status;
                    if (status == 0) { //跳转已确认页面
                        wx.redirectTo({
                            url: '../feastPage/notActivated/notActivated?activityInfo=' + JSON.stringify(res.data.data) + '&isBanquetMaster=' + isNewBanquetMaster,
                        })
                        return;

                    }else    if (status == 3 || status == 2||status ==4) { //跳转扫码激活页面
                        wx.redirectTo({
                            url: '../feastPage/activated/activated?activityInfo=' + JSON.stringify(res.data.data)
                        })
                        return;
                    }else{
                        wx.redirectTo({
                          url: '/pages/jingdianPage/prompt/prompt',
                        })
                    }


                } else {
                    wx.showToast({
                        title: '操作失败，稍后重试',
                        icon: 'none'
                    })
                }
            },
            fail: function (res) {
                wx.showToast({
                    title: '操作失败，稍后重试',
                    icon: 'none'
                })
            }
        });
    },
    bindFeast(isNewBanquetMaster) {
        console.log('bindFeast==>'+isNewBanquetMaster)
        const that = this;
        netWork.POST_Json('banquet/bindMaster', {
            data: {
                userId: wx.getStorageSync('userId'),
                qrcodeAPublish: wx.getStorageSync('qrCodeFeast'),
                masterPhone: wx.getStorageSync('userPhone'),
            },
            success: function (res) {
                if (res.data.retCode == undefined) {
                    wx.redirectTo({
                        url: '/pages/jingdianPage/prompt/prompt',
                    })
                }
                if (res.data.retCode == '0000') {
                    that.queryInfo(isNewBanquetMaster);
                } else {
                    wx.redirectTo({
                        url: '/pages/feastPage/notThisFeast/notThisFeast?msg=' + res.data.retMsg,
                    })
                }
            },
            fail: function (res) {
                wx.redirectTo({
                    url: '/pages/jingdianPage/prompt/prompt',
                })
            }
        });
    },
    getLastScanProductType: function () {
        let lastProductType = 1;
        return new Promise((resolve, reject) => {

            netWork.POST('/getLastScanProductType', {
                data: {
                    userId: wx.getStorageSync('userId')
                },
                success: function (res) {
                    if (res.data.retCode == "0000") {
                        if (res.data.data) {
                            lastProductType = res.data.data.productType;
                        }

                    }
                    resolve(lastProductType);
                },
                fail: function () {
                    resolve(lastProductType);
                }
            })
        })
    },

})